import router from "@/router";
// 路由
import { DynamicRoutes } from '@/router/routesFile'
import { clone } from "@/utils/util";
import { setDefaultRouter, routerFilterFunc } from "@/utils/handleRouter";
import permissionList from "@/utils/permission";


const state = {
  permissionList: null /** 所有路由 */,
  sidebarMenu: [] /** 导航菜单 */,
  currentMenu: "" /** 当前active导航菜单 */,
  isSidebarNavCollapse: false,  /* 导航菜单是否折叠 */
  crumbList: [],  /* 面包屑导航列表 */
}

const mutations: any = {
  /* 设置菜单 */
  SET_MENU(state: any, menu: any[]) {
    console.log(state);
    state.sidebarMenu = menu
  },
  /* 完整的路由表 */
  SET_PERMISSION(state: any, routes: Array<any>) {
    state.permissionList = routes
  },
  //当前选中的导航
  SET_CURRENT_MENU(state: any, currentMenu: string) {
    state.currentMenu = currentMenu
  },
  //导航栏是否折叠
  toggleNavCollapse(state: any) {
    state.isSidebarNavCollapse = !state.isSidebarNavCollapse
  },
  /* 面包屑导航列表 */
  setCrumbList(state: any, list: Array<any>) {
    state.crumbList = list
  }
}

const actions: any = {
  async FETCH_PERMISSION({ commit }: any) {
    // 处理动态路由
    const routes: any[] = routerFilterFunc(permissionList)
    // 不需要动态路由
    const mainContainer: any = clone(DynamicRoutes).find(
      (v: any) => v.path === ""
    );
    let children: any[] = []
    children = mainContainer.children
    // 连接动态动态路由
    children = children.concat(routes)
    // 提交到vuex仓库管理 
    commit("SET_MENU", children)
    mainContainer.children = children
    setDefaultRouter([mainContainer])
    let initalRoutes: any[] = router.options.routes
    // 添加路由 
    router.addRoute(mainContainer)
    commit("SET_PERMISSION", [...initalRoutes, ...DynamicRoutes])
  }
}

const getters = {
  GET_MENU: (state: any) => state.sidebarMenu, // 菜单
  GET_CURRENTMENU: (state: any) => state.currentMenu, // 当前菜单
  getCrumbList: (state: any) => state.crumbList, // 面包屑
  getIsSidebarNavCollapse: (state: any) => state.isSidebarNavCollapse, // 是否折叠
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};
